// eventBus.ts
type EventHandler = (...args: any[]) => void;

class EventBus {
  private events: Map<string, EventHandler[]> = new Map();

  emit(event: string, ...args: any[]): void {
    const handlers = this.events.get(event);
    if (!handlers) return;
    [...handlers].forEach((handler) => handler(...args));
  }

  off(event: string, handler?: EventHandler): void {
    if (handler) {
      const handlers = this.events.get(event);
      if (!handlers) return;
      const idx = handlers.indexOf(handler);
      if (idx !== -1) handlers.splice(idx, 1);
      if (handlers.length === 0) this.events.delete(event);
      else this.events.set(event, handlers);
    } else {
      this.events.delete(event);
    }
  }

  on(event: string, handler: EventHandler): void {
    const handlers = this.events.get(event) || [];
    handlers.push(handler);
    this.events.set(event, handlers);
  }
}

// 单例
const eventBus = new EventBus();

// 挂载到window上，带上类型声明
declare global {
  interface Window {
    eventBus: EventBus;
  }
}
window.eventBus = eventBus;

export default eventBus;
